# coding:utf-8

from bson import ObjectId
import tornado
from tornado import gen
from tornado.web import HTTPError

from handler.api import errors
from handler.api.base import BaseHandler

import config
from data.redis import redis
from data.mongo import col_samples_01,col_vibration_leve,col_max_acceleration,col_event,col_event_data,col_event_data_mqtt,col_event_mqtt,col_level_data_mqtt
from data.mysql import mysqldb_conn

from datetime import datetime, timedelta
import json
import struct

class testMysqlHandler(BaseHandler):
    def get(self):
        #####!!!!!     username = self.get_argument('username')
        #####!!!!!     workPointIDs = self.get_argument('workPointIDs')
        #####!!!!!     #获取游标
        #####!!!!!     mysqldb_vibration_cur = mysqldb_conn.cursor()
        #####!!!!!     
        #####!!!!!     # 查询用户ID
        #####!!!!!     useId_list = []
        #####!!!!!     
        #####!!!!!     sql = "select distinct id from cms_user where username = '%s' "
        #####!!!!!     data = (username,)
        #####!!!!!     mysqldb_vibration_cur.execute(sql % data)        
        #####!!!!!     for row in mysqldb_vibration_cur.fetchall():
        #####!!!!!         useId_list.append(row[0])
        #####!!!!!         #print(row)
        #####!!!!!         
        #####!!!!!     #依据用户ID查询该用户下的工点ID
        #####!!!!!     workPointID_list = []
        #####!!!!!     sql="select distinct work_id from cms_user_work WHERE user_id in ({})".format( ','.join(["%d" % item for item in useId_list]) )
        #####!!!!!     mysqldb_vibration_cur.execute(sql)
        #####!!!!!     #print(sql)
        #####!!!!!     for row in mysqldb_vibration_cur.fetchall():
        #####!!!!!         workPointID_list.append(row[0])
        #####!!!!!         #print(row)
        #####!!!!!         
        #####!!!!!     #依据工点ID查询采集器ID
        #####!!!!!     collectors_list = []
        #####!!!!!     collectorsID_list = []
        #####!!!!!     sql="select distinct id, collectors_id from cms_collectors WHERE work_id in ({})".format( ','.join(["%d" % item for item in workPointID_list]) )
        #####!!!!!     mysqldb_vibration_cur.execute(sql)
        #####!!!!!     #print(sql)
        #####!!!!!     for row in mysqldb_vibration_cur.fetchall():
        #####!!!!!         collectorsID_list.append(row[0])
        #####!!!!!         collectors_list.append( {"id":row[0], "collectors_id":row[1]} )
        #####!!!!!         #print(row)
        #####!!!!!         
        #####!!!!!     #依据采集器ID查询传感器
        #####!!!!!     sensor_list = []
        #####!!!!!     sql="select distinct id, sensor_id, sensitivity, collectors_id, channel_id from cms_sensor WHERE collectors_id in ({})".format( ','.join(["%d" % item for item in collectorsID_list]) )
        #####!!!!!     mysqldb_vibration_cur.execute(sql)
        #####!!!!!     #print(sql)
        #####!!!!!     for row in mysqldb_vibration_cur.fetchall():
        #####!!!!!         sensor_list.append( {"id":row[0], "sensor_id":row[1], "sensitivity":row[2], "collectors_id":row[3], "channel_id":row[4]} )
        #####!!!!!         #print(row)
        #####!!!!!     
        #####!!!!!     #关闭游标        
        #####!!!!!     mysqldb_vibration_cur.close()
        #####!!!!!     
        #####!!!!!     #整合传感器ID
        #####!!!!!     collectorsIDs = []
        #####!!!!!     collectorsIDs_old = []
        #####!!!!!     for i in range( len(sensor_list) ):
        #####!!!!!         for j in range( len(collectors_list) ):
        #####!!!!!             if str( collectors_list[j]['id'] ) == sensor_list[i]['collectors_id']:
        #####!!!!!                 collectorsIDs.append( sensor_list[i]['sensor_id'] )
        #####!!!!!                 collectorsIDs_old.append( collectors_list[j]['collectors_id'][4:-1] + "_" + sensor_list[i]['channel_id'] )
        #####!!!!!     
        #####!!!!!     data_json = {#"useId_list":useId_list, "workPointID_list":workPointID_list,"collectorsID_list":collectorsID_list,"collectors_list":collectors_list,
        #####!!!!!                  "collectorsIDs":collectorsIDs,
        #####!!!!!                  "collectorsIDs_old":collectorsIDs_old}
        data_json = {"freq":getFreq("N19002003")}
        self.write_json(data_json)
        
#依据用户名查找该用户下工点挂载的传感器
#输入参数：username
#输出参数：collectorsID = {"collectorsIDs":collectorsIDs,          应用后台配置传感器编号列表
#                          "collectorsIDs_old":collectorsIDs_old}  数据平台对应的传感器编号列表
def find_collectorsID(username):
    #获取游标
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    mysqldb_conn.ping(reconnect=True)
    # 查询用户ID
    useId_list = []
    sql = "select distinct id from cms_user where username = '" + username + "' "
    #print("find_collectorsID-cms_user sql is:" + sql)
    mysqldb_vibration_cur.execute(sql)        
    for row in mysqldb_vibration_cur.fetchall():
        useId_list.append(row[0])
        #print(row)
        
    #依据用户ID查询该用户下的工点ID
    workPointID_list = []
    sql="select distinct work_id from cms_user_work WHERE user_id in ({})".format( ','.join(["%d" % item for item in useId_list]) )
    mysqldb_vibration_cur.execute(sql)
    #print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        workPointID_list.append(row[0])
        #print(row)
        
    #依据工点ID查询采集器ID
    collectors_list = []
    collectorsID_list = []
    sql="select distinct id, collectors_id from cms_collectors WHERE work_id in ({})".format( ','.join(["%d" % item for item in workPointID_list]) )
    mysqldb_vibration_cur.execute(sql)
    #print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        collectorsID_list.append(row[0])
        collectors_list.append( {"id":row[0], "collectors_id":row[1]} )
        #print(row)
        
    #依据采集器ID查询传感器
    sensor_list = []
    sql="select distinct id, sensor_id, sensitivity, collectors_id, channel_id from cms_sensor WHERE collectors_id in ({})".format( ','.join(["%d" % item for item in collectorsID_list]) )
    mysqldb_vibration_cur.execute(sql)
    #print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        sensor_list.append( {"id":row[0], "sensor_id":row[1], "sensitivity":row[2], "collectors_id":row[3], "channel_id":row[4]} )
        #print(row)
    
    #关闭游标        
    mysqldb_vibration_cur.close()
    
    #整合传感器ID
    collectorsIDs = []
    collectorsIDs_old = []
    mqtt_flag_list=[]
    mqtt_check_list=[]
    
    with open('service_config_new.json', 'r') as f:
        config = f.read()
    service_config = json.loads(config)
    GateWayList=service_config["GateWayList"]
    
    for item_GateWay in GateWayList:
        if item_GateWay['mqtt_flag'] != 0:
            mqtt_flag_list.append(item_GateWay['GateWayID'])
    
    for i in range( len(sensor_list) ):
        for j in range( len(collectors_list) ):
            if str( collectors_list[j]['id'] ) == sensor_list[i]['collectors_id']:
                collectorsIDs.append( sensor_list[i]['sensor_id'] )
                temp_collectorsID = collectors_list[j]['collectors_id'].split('_')
                collectorsIDs_old.append( temp_collectorsID[-1] + "_" + sensor_list[i]['channel_id'] )
                if temp_collectorsID[-1] in mqtt_flag_list:
                    mqtt_check_list.append(1)
                else:
                    mqtt_check_list.append(0)
                
    
    
    collectorsID = {"collectorsIDs":collectorsIDs,
                 "collectorsIDs_old":collectorsIDs_old,
                 "mqtt_check_list":mqtt_check_list}
    return collectorsID

#传感器编号转换函数，从配置数据库读取采集器啊编号与通道号，完成应用后台配置传感器编号到数据平台对应的传感器编号的转换
#输入参数：应用后台配置传感器编号sensorID
#输出参数：数据平台对应的传感器编号transformationResult
def transformationSensorID_bak(sensorID):
    transformationResult=""
    
    #获取游标
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    mysqldb_conn.ping(reconnect=True)
    #依据配置的传感器编号查找采集器编号
    print("------------------"+sensorID)
    sql = "select distinct collectors_id, channel_id from cms_sensor where sensor_id = '" + sensorID +"' "
    #data = (sensorID,)
    mysqldb_vibration_cur.execute(sql)
    collectors_id_list=[]
    channel_id_list =[]
    for row in mysqldb_vibration_cur.fetchall():        
        channel_id_list.append(row[1])
        collectors_id_list.append(int(row[0]))
        
    sql = "select distinct collectors_id from cms_collectors where id in ({})".format( ','.join(["%d" % item for item in collectors_id_list]) )
    print("====="+ sql)
    mysqldb_vibration_cur.execute(sql)
    collectors_id_old_list=[]
    for row in mysqldb_vibration_cur.fetchall():
        collectors_id_old_list.append(row[0])
    
    #关闭游标        
    mysqldb_vibration_cur.close()
    
    mqtt_flag_list=[]
    mqtt_flag=0
    
    with open('service_config_new.json', 'r') as f:
        config = f.read()
    service_config = json.loads(config)
    GateWayList=service_config["GateWayList"]
    
    for item_GateWay in GateWayList:
        if item_GateWay['mqtt_flag'] != 0:
            mqtt_flag_list.append(item_GateWay['GateWayID'])
    
    if ( len(channel_id_list)>0 and len(collectors_id_old_list)>0 ):
        temp_collectorsID = collectors_id_old_list[0].split('_')
        transformationResult = temp_collectorsID[-1] + "_" + channel_id_list[0]
        if temp_collectorsID[-1] in mqtt_flag_list:
            mqtt_flag = 1
    result_item={"sensorID":transformationResult, "mqtt_flag":mqtt_flag}
    return result_item
    
def transformationSensorID(sensorID):
    transformationResult=""
    with open('service_config_new.json', 'r') as f:
        config = f.read()
    service_config = json.loads(config)
    GateWayList=service_config["GateWayList"]
    sensorList=[]        
    for item in GateWayList:
        j=0
        for i in item["ConnectList"]:
            j+=1
            if i == sensorID:
                #数据平台对应的传感器编号
                transformationResult=item["GateWayID"]+"_0"+str(j)
    return transformationResult

#获取应用后台配置的采集频率
#输入参数：应用后台配置传感器编号sensorID
#输出参数：应用后台配置的感器编号sensorID对应的通道对应的频率freq
def getFreq(sensorID):
    #获取游标
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    
    # 查询collectors_id与channel_id
    sql = "select distinct collectors_id, channel_id from cms_sensor where sensor_id = '" + sensorID + "' "
    collectors_id = ""
    channel_id    = ""
    print(sql)
    mysqldb_vibration_cur.execute(sql)        
    for row in mysqldb_vibration_cur.fetchall():
        collectors_id = row[0]
        channel_id    = row[1]
        #print(row)
        
    #依据collectors_id(内部编号)查询对应的编号eg:MCC_01E2C847
    sql = "select distinct collectors_id from cms_collectors where id = " + str(collectors_id) + ";"    
    collectors_name = ""
    mysqldb_vibration_cur.execute(sql)
    print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        collectors_name = row[0]
        #print(row)
        
    #依据采集器编号与通道号查询配置频率
    sql = "select distinct jihz from cms_collectors_conf where collectors_id = '" + collectors_name + "' and channel_id = '" + channel_id + "'"
    
    freq_list = []
    mysqldb_vibration_cur.execute(sql)
    print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        freq_list.append(row[0])
        
    #关闭游标        
    mysqldb_vibration_cur.close()
    
    freq = 0
    if len(freq_list) > 0:
        freq = freq_list[0]
    
    return freq

#计算分位置
#输入参数 数据平台对应的传感器编号：sensorID，实时振级数据表名：vibration_leve_co_name, 开始时间startTime_str，结束时间：endTime_str
def tantileCount(sensorID, vibration_leve_co_name, startTime_str, endTime_str, mqtt_flag):
    #print("begin!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    resultList=[]    
    sampleList=[]
    if mqtt_flag != 0:
        vibration_leve_data=col_level_data_mqtt.find({"sensorID":sensorID,"samples_time":{"$gte":startTime_str,"$lte":endTime_str}}).sort([("samples_time",1)])    
        for item_2 in vibration_leve_data:
            sampleList += item_2['vibration_level']
        vibration_leve_data.close()
    else:
        vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime_str,"$lte":endTime_str}}).sort([("samples_time",1)])        
        for item_2 in vibration_leve_data:
            sampleList.append(item_2['vibration_leve'])
        vibration_leve_data.close()
    
    sampleListLength=len(sampleList)
    #print(sampleListLength)
    sampleList.sort(reverse=True)
    resultNumber = int( 0.01*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.05*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.1*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
    
    resultNumber = int( 0.2*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.3*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.4*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.5*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
    #print(resultList)
    #print("end!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    return resultList

#实时计算分位值
#输入参数：应用后台配置传感器编号sensorID
#输出参数：分位值列表
class GetRealTimeTantileBySensorIDHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        time_from = self.get_argument('time_from')
        time_to = self.get_argument('time_to')
        
        data_json = {}
        if len(time_from) == 0 or len(time_to) == 0:
            data_json = {"EOFError":"请输入时间段!"}
        else:            
            trans_result = transformationSensorID_bak(sensorID)
            sensorID_old = trans_result['sensorID']
            vibration_leve_co_name = "vibration_leve_"+sensorID_old
            tantile_list=tantileCount(sensorID_old, vibration_leve_co_name, time_from, time_to, trans_result['mqtt_flag'])
            #temp_tantileList=[91.24,61.75,58.33,57.26,57.05,56.86,56.62]
            y_list=[1,5,10,20,30,40,50]
            data_json = {"tantile_list":tantile_list, "y_list":y_list}
        self.write_json(data_json)

#实时计算超限比例
#输入参数：应用后台配置传感器编号sensorID
#输出参数：分位值列表
class GetUltralimitBySensorIDHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        time_from = self.get_argument('time_from')
        time_to = self.get_argument('time_to')
        ultralimit = float(self.get_argument('ultralimit'))
        count_num = 0
        data_length = 1
        data_json = {}
        if len(time_from) == 0 or len(time_to) == 0 or ultralimit <= 0:
            data_json = {"EOFError":"请输入时间错误，或阈值错误(>0)!"}
        else:
            trans_result = transformationSensorID_bak(sensorID)
            sensorID_old = trans_result['sensorID']
            print(sensorID_old)
            sampleList=[]
            if trans_result['mqtt_flag'] != 0:
                vibration_leve_data=col_level_data_mqtt.find({"sensorID":sensorID_old,"samples_time":{"$gte":time_from,"$lte":time_to}}).sort([("samples_time",1)])    
                for item_2 in vibration_leve_data:
                    sampleList += item_2['vibration_level']
                vibration_leve_data.close()
            else:
                vibration_leve_co_name="vibration_leve_"+sensorID_old
                vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":time_from,"$lte":time_to}}).sort([("samples_time",1)])        
                for item_2 in vibration_leve_data:
                    sampleList.append(item_2['vibration_leve'])
                vibration_leve_data.close()
            data_length = len(sampleList)
            for k in range(data_length):
                if sampleList[k] > ultralimit:
                    count_num+=1
        data_json = {"ultralimit":round( count_num/data_length*100,2 )}
        self.write_json(data_json)

class GetLastCollecetTimeHandler_bak(BaseHandler):
    def get(self):
    
        # 读取配置
        with open('service_config_new.json', 'r') as f:
            config = f.read()
        service_config = json.loads(config)
        GateWayList=service_config["GateWayList"]
        
        sensorList=[]
        
        for item in GateWayList:
            j=0
            for i in item["ConnectList"]:
                j+=1
                if i != '':
                    #传感器编号
                    sensorID=item["GateWayID"]+"_0"+str(j)
                    
                    redis_last_time=""
                    samples_time_key="last_second_samples_" + sensorID
                    redis_last_time_list=redis.lrange(samples_time_key,0,1)
                    if len(redis_last_time_list) > 0:
                        redis_last_time=json.loads(redis.lrange(samples_time_key,0,1)[0])["samples_time"]
                    item1={"sensorID":i,"lastCollectTime":redis_last_time,"onLineFlag":1}
                    sensorList.append(item1)
        item1={"sensorID":"N19001026","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19001028","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"DH2620","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"DH2621","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"DH2622","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"DH2623","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19001033","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19001034","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19001035","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19001036","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        item1={"sensorID":"N19002001","lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
        sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)
        
class GetLastCollecetTimeHandler(BaseHandler):
    def get(self):
        #username = self.get_argument('username')
        username = "users"
        collectorsID = find_collectorsID(username)
        #print(collectorsID)
        collectorsIDs = collectorsID['collectorsIDs']#后台配置传感器编号
        collectorsIDs_old = collectorsID['collectorsIDs_old']#后台配置传感器编号对应的 ‘采集器编号’+‘通道号’
        sensorList=[]
        if len(collectorsIDs) > 0 and len(collectorsIDs_old) > 0:
            for i in range( len( collectorsIDs_old ) ):
                redis_last_time=""
                samples_time_key="last_second_vibration_level_" + collectorsIDs_old[i]
                #print("==========================================")
                #print(samples_time_key)
                level_time = redis.get(samples_time_key)
                #print(type(level_time))
                #print(level_time)
                if None == level_time:
                    item1={"sensorID":collectorsIDs[i],"lastCollectTime":"2020-09-04 16:15:25","onLineFlag":0}
                    sensorList.append(item1)
                else:
                    redis_last_time_dic=eval(level_time)
                    redis_last_time = redis_last_time_dic["samples_time"]
                    time_1_struct=datetime.strptime(redis_last_time,'%Y-%m-%d %H:%M:%S')#采集最新时间
                    time_2_struct=datetime.now().replace( microsecond=0)
                    seconds = (time_2_struct - time_1_struct).seconds
                    if seconds >= 10:#10秒无数据回传判定为离线
                        item1={"sensorID":collectorsIDs[i],"lastCollectTime":redis_last_time,"onLineFlag":0}
                    else:
                        item1={"sensorID":collectorsIDs[i],"lastCollectTime":redis_last_time,"onLineFlag":1}
                    sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

class GetRealTimeVibrationLeveHandler_bak(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        sensorID = transformationSensorID(sensorID)
        #print(sensorID)
        samples_data_key = "last_second_vibration_level_" + sensorID
        
        redis_last_vibration_leve_time=[]
        redis_last_vibration_leve_data=[]
        
        samples_data=json.loads(redis.get(samples_data_key))
        redis_last_vibration_leve_time.append(samples_data['samples_time'])
        redis_last_vibration_leve_data = list(map(lambda x:x['vibration_leve'],samples_data['data']))
        data_json = {"vibrationLeveList":[{"time":redis_last_vibration_leve_time},
                                          {"data":redis_last_vibration_leve_data}]}
        self.write_json(data_json)
        
class GetRealTimeVibrationLeveHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        #sensorID = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID = trans_result['sensorID']
        #print(sensorID)
        samples_data_key = "last_second_vibration_level_" + sensorID
        
        redis_last_vibration_leve_time=[]
        redis_last_vibration_leve_data=[]
        
        samples_data=json.loads(redis.get(samples_data_key))
        redis_last_vibration_leve_time.append(samples_data['samples_time'])
        redis_last_vibration_leve_data = list(map(lambda x:x['vibration_leve'],samples_data['data']))
        data_json = {"vibrationLeveList":[{"time":redis_last_vibration_leve_time},
                                          {"data":redis_last_vibration_leve_data}]}
        self.write_json(data_json)

class GetSensorEventStatisticsHandler(BaseHandler):
    def get(self):
        sensorList=[]
        sensorID = self.get_argument('sensorID')
        #sensorID_old = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']
        ###peakLimitCount=col_event.find({"sensorID":sensorID_old,"eventType":1}).count()
        ###vibrationLimit1=col_event.find({"sensorID":sensorID_old,"eventType":2}).count()
        ###vibrationLimit2=col_event.find({"sensorID":sensorID_old,"eventType":3}).count()
        ###item1={"sensorID":sensorID,\
        ###         "peakLimitCount":peakLimitCount,\
        ###         "vibrationLimit1":vibrationLimit1,\
        ###         "vibrationLimit2":vibrationLimit2}
        ###sensorList.append(item1)
        ###print(sensorList)
        if trans_result['mqtt_flag'] != 0:#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01'  or sensorID_old == '01E4FA37_03':
            #查询事件回传数据库
            col_event_mqtt
            peakLimitCount=col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1}).count()
            vibrationLimit1=col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2}).count()
            vibrationLimit2=col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3}).count()
            item1={"sensorID":sensorID,\
                     "peakLimitCount":peakLimitCount,\
                     "vibrationLimit1":vibrationLimit1,\
                     "vibrationLimit2":vibrationLimit2}
            sensorList.append(item1)
        else:
            peakLimitCount=col_event.find({"sensorID":sensorID_old,"eventType":1}).count()
            vibrationLimit1=col_event.find({"sensorID":sensorID_old,"eventType":2}).count()
            vibrationLimit2=col_event.find({"sensorID":sensorID_old,"eventType":3}).count()
            item1={"sensorID":sensorID,\
                     "peakLimitCount":peakLimitCount,\
                     "vibrationLimit1":vibrationLimit1,\
                     "vibrationLimit2":vibrationLimit2}
            sensorList.append(item1)
        
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

        
class GetSensorEventStatistics24HoursHandler(BaseHandler):
    def get(self):
        sensorList=[]
        sensorID = self.get_argument('sensorID')
        #sensorID_old = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']

        current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0)
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        #print(current_tiem)
        for i in range(24):
            countTimeEnd=current_tiem + timedelta( hours = (0-i) )
            countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            countTimeBegin=current_tiem + timedelta(hours = (0-i-1) )
            countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            #print("countTimeBegin_str")
            #print(countTimeBegin_str)
            #print("countTimeEnd_str")
            #print(countTimeEnd_str)
            EndTimeList.append(countTimeEnd_str)
            #BeginTimeList.append(countTimeBegin_str)
            if trans_result['mqtt_flag'] != 0:
                peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit1Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit2Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
            else:
                peakLimitEvent.append( col_event.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit1Event.append( col_event.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit2Event.append( col_event.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
            
            BeginTimeList.append(countTimeBegin_str[11:16])
        EndTimeList.reverse()
        BeginTimeList.reverse()
        peakLimitEvent.reverse()
        vibrationLimit1Event.reverse()
        vibrationLimit2Event.reverse()
        item1={"sensorID":sensorID,\
                 "EndTimeList":EndTimeList,\
                 "BeginTimeList":BeginTimeList,\
                 "peakLimitEvent":peakLimitEvent,\
                 "vibrationLimit1Event":vibrationLimit1Event,\
                 "vibrationLimit2Event":vibrationLimit2Event}
        sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

class GetSensorEventListHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        #sensorID_old = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']
        peakLimit = self.get_argument('peakLimit_1')
        limit_1 = self.get_argument('limit_1')
        limit_2 = self.get_argument('limit_2')
        limit_3 = self.get_argument('limit_3')
        
        limit = self.get_argument('limit')
        offset = self.get_argument('offset')
        
        time_from = self.get_argument('time_from')
        time_to = self.get_argument('time_to')
        #print(type(time_from))
        #print(len(time_from))
        if len(time_from) == 0:
            time_from = "1900-01-01 01:01:01.0"
        if len(time_to) == 0:
            time_to = "2999-12-31 23:59:59.9"
        event_list=[]
        
        if trans_result['mqtt_flag'] != 0:#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01' or sensorID_old == '01E4FA37_03':
            event_data=col_event_mqtt.find({"sensorID":sensorID_old, "eventStartTime":{"$gte":time_from, "$lte":time_to}, 'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).limit(int(limit)).skip(int(offset))
            event_data_count=col_event_mqtt.find({"sensorID":sensorID_old, "eventStartTime":{"$gte":time_from, "$lte":time_to}, 'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).count()
            for item in event_data:                
                item["sensorID"]=sensorID
                item["time_dif"]=round(item["time_dif"],1)
                item["eventNum"]=item["eventNum"][8:26]
                event_list.append(item)
            data_json = {"eventList":event_list,"total":event_data_count}
            self.write_json(data_json)
        else:
            event_data=col_event.find({"sensorID":sensorID_old, "eventStartTime":{"$gte":time_from, "$lte":time_to}, 'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).limit(int(limit)).skip(int(offset))
            event_data_count=col_event.find({"sensorID":sensorID_old,  "eventStartTime":{"$gte":time_from, "$lte":time_to}, 'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).count()
            for item in event_data:
                item["sensorID"]=sensorID
                item["time_dif"]=round(item["time_dif"],1)
                item["eventNum"]=item["eventNum"]
                event_list.append(item)
            data_json = {"eventList":event_list,"total":event_data_count}
            self.write_json(data_json)
        #print(event_data_count)
        #print(event_data)
        
        ######for item in event_data:
        ######    item["sensorID"]=sensorID
        ######    item["time_dif"]=round(item["time_dif"],1)
        ######    item["eventNum"]=item["eventNum"][8:26]
        ######    event_list.append(item)
        ######data_json = {"eventList":event_list,"total":event_data_count}
        ######self.write_json(data_json)

class GetSensorEventStatistics30DaysHandler(BaseHandler):
    def get(self):
        sensorList=[]
        sensorID = self.get_argument('sensorID')
        #sensorID_old = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']

        current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0,hour=0)
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        #print(current_tiem)
        for i in range(30):
            countTimeEnd=current_tiem + timedelta( days = (0-i) )
            countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            countTimeBegin=current_tiem + timedelta(days = (0-i-1) )
            countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            #print("countTimeBegin_str")
            #print(countTimeBegin_str)
            #print("countTimeEnd_str")
            #print(countTimeEnd_str)
            EndTimeList.append(countTimeEnd_str[0:10])
            BeginTimeList.append(countTimeBegin_str[0:10])
            if trans_result['mqtt_flag'] != 0:
                peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit1Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit2Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
            else:
                peakLimitEvent.append( col_event.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit1Event.append( col_event.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                vibrationLimit2Event.append( col_event.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
        EndTimeList.reverse()
        BeginTimeList.reverse()
        peakLimitEvent.reverse()
        vibrationLimit1Event.reverse()
        vibrationLimit2Event.reverse()
        item1={"sensorID":sensorID,\
                 "EndTimeList":EndTimeList,\
                 "BeginTimeList":BeginTimeList,\
                 "peakLimitEvent":peakLimitEvent,\
                 "vibrationLimit1Event":vibrationLimit1Event,\
                 "vibrationLimit2Event":vibrationLimit2Event}
        sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

class GetEventVibrationLeveHandler(BaseHandler):
    def get(self):
        #print(datetime.datetime.now())
        sensorID = self.get_argument('sensorID')

        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']
        eventNum = self.get_argument('eventNum')
        #startTime = self.get_argument('StartTime')
        #endTime = self.get_argument('EndTime')
        if trans_result['mqtt_flag'] !=0:#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01'  or sensorID_old == '01E4FA37_03':
            eventNum = sensorID_old[0:8] + eventNum
            event_title=col_event_mqtt.find({"sensorID":sensorID_old, "eventNum":eventNum})
            startTime = ""
            endTime = ""
            for item_1 in event_title:
                startTime = item_1["eventStartTime"][0:19]
                endTime = item_1["eventEndTime"][0:19]
                print(startTime)
                print(endTime)
            vibration_leve_data=col_level_data_mqtt.find( { "sensorID":sensorID_old,"samples_time":{"$gte":startTime,"$lte":endTime} } ).sort([("samples_time",1)])
            time_list=[]
            data_list=[]
            for item_2 in vibration_leve_data:                
                for k in range(len( item_2['vibration_level'] )):
                    time_list.append( (datetime.strptime(item_2["samples_time"],'%Y-%m-%d %H:%M:%S') + timedelta( seconds = k*0.1 )).strftime("%Y-%m-%d %H:%M:%S.%f")[0:21] )
                    data_list.append(item_2['vibration_level'][k])
            vibration_leve_data.close()
            data_json = {"vibrationLeveList":[{"time":time_list},
                                              {"data":data_list}]}
            #print(time_list)
            #print(data_list)
            self.write_json(data_json)
        else:
            samples_data=col_event_data.find({"sensorID":sensorID_old,"eventNum":eventNum}).sort([("order_number",1)])#.limit(1)#"eventStartTime":startTime,
            str_item=''
            data_list_num=0
            for item_2 in samples_data:
                startTime=item_2["eventStartTime_1"]
                data_list_num=data_list_num + len(item_2['data'])
            str_item=startTime
            start_time=datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
            samples_data.close()
            end_time=start_time+timedelta(seconds=0.0005*data_list_num)
            endTime=end_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:23]
            
            #print(start_time)
            #print(endTime)
            
            vibration_leve_co_name="vibration_leve_"+sensorID_old
            
            vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime,"$lte":endTime}}).sort([("samples_time",1)])
            #print(vibration_leve_co_name)
            time_list=[]
            data_list=[]
            str_item=''
            for item_2 in vibration_leve_data:
                data_list.append(item_2['vibration_leve'])
                time_list.append(item_2["samples_time"])
            vibration_leve_data.close() 
            #print(len(data_list))
            data_json = {"vibrationLeveList":[{"time":time_list},
                                              {"data":data_list}]}
            #print(time_list)
            #print(data_list)
            self.write_json(data_json)

class GetEventDetailDataHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        #sensorID_old = transformationSensorID_bak(sensorID)
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']
        eventNum = self.get_argument('eventNum')
        
        if trans_result['mqtt_flag'] != 0:#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01'  or sensorID_old == '01E4FA37_03':
            eventNum = sensorID_old[0:8] + eventNum
            print(eventNum)
            samples_data=col_event_data_mqtt.find({"eventNum":eventNum}).sort([("samples_time",1)])
            time_list=[]
            data_list=[]
            str_item=''
            for item_2 in samples_data:
                for k in range( len( item_2['samples_data'] ) ):
                    time_list.append( (datetime.strptime(item_2["samples_time"],'%Y-%m-%d %H:%M:%S') + timedelta( seconds = k*0.0005 )).strftime("%Y-%m-%d %H:%M:%S.%f")[0:24] )
                    data_list.append(item_2['samples_data'][k])            
            
            samples_data.close()
            temp_last_time = time_list[-1]
            temp_last_data = data_list[-1]
            time_list.append( (datetime.strptime(temp_last_time,'%Y-%m-%d %H:%M:%S.%f') + timedelta(seconds=0.0005)).strftime("%Y-%m-%d %H:%M:%S.%f")[0:24] )
            print( (datetime.strptime(temp_last_time,'%Y-%m-%d %H:%M:%S.%f') + timedelta(seconds=0.0005)).strftime("%Y-%m-%d %H:%M:%S.%f")[0:24] )
            data_list.append(temp_last_data)
            data_json = {"vibrationLeveList":[{"time":time_list},
                                              {"data":data_list}]}
            self.write_json(data_json)
        else:
            samples_data=col_event_data.find({"sensorID":sensorID_old,"eventNum":eventNum}).sort([("order_number",1)])
            time_list=[]
            data_list=[]
            str_item=''
            for item_2 in samples_data:
                data_list=data_list + item_2['data']
                str_item=item_2["eventStartTime_1"]
            #print(str_item)
            start_time=datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
            samples_data.close()  
            for j in range(len(data_list)):
                sing_time=start_time+timedelta(seconds=0.0005*j)
                sing_time_str=sing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:24]
                time_list.append(sing_time_str)
            temp_last_time = time_list[-1]
            temp_last_data = data_list[-1]
            time_list.append( (datetime.strptime(temp_last_time,'%Y-%m-%d %H:%M:%S.%f') + timedelta(seconds=0.0005)).strftime("%Y-%m-%d %H:%M:%S.%f")[0:24] )
            data_list.append(temp_last_data)
            data_json = {"vibrationLeveList":[{"time":time_list},
                                              {"data":data_list}]}
            self.write_json(data_json)

class GetTantileBySensorHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        trans_result = transformationSensorID_bak(sensorID)
        sensorID_old = trans_result['sensorID']
        cycleType = self.get_argument('cycleType')
        vibration_leve_co_name="vibration_leve_"+sensorID_old
        
        resultList=[]
        
        endTime = datetime.now().replace( microsecond=0,second=0,minute=0)
        endTime_str=endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        #print(endTime_str)
        startTime_str=""
        if cycleType == "0":#按天
            tantileList=[]
            startTime=endTime + timedelta( hours = -1 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            tantileList.append("近1小时")
            tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, trans_result['mqtt_flag'])
            item1={"cycleTime":2, "tantileList":tantileList}
            resultList.append(tantileList)
            
            tantileList=[]
            startTime=endTime + timedelta( hours = -2 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            tantileList.append("近2小时")
            tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, trans_result['mqtt_flag'])
            item1={"cycleTime":4, "tantileList":tantileList}
            resultList.append(tantileList)
            
            tantileList=[]
            startTime=endTime + timedelta( hours = -4 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            tantileList.append("近4小时")
            tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, trans_result['mqtt_flag'])
            item1={"cycleTime":8, "tantileList":tantileList}
            resultList.append(tantileList)
            
            tantileList=[]
            startTime=endTime + timedelta( hours = -8 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            tantileList.append("近8小时")
            tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, trans_result['mqtt_flag'])
            item1={"cycleTime":12, "tantileList":tantileList}
            resultList.append(tantileList)
            
            tantileList=[]
            startTime=endTime + timedelta( hours = -24 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            tantileList.append("近24小时")
            tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, trans_result['mqtt_flag'])
            item1={"cycleTime":16, "tantileList":tantileList}
            resultList.append(tantileList)
            
            # tantileList=[]
            # startTime=endTime + timedelta( hours = -20 )
            # startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            # tantileList.append("近20小时")
            # tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str)
            # item1={"cycleTime":20, "tantileList":tantileList}
            # resultList.append(tantileList)
            # tantileList=[]
            # startTime=endTime + timedelta( hours = -24 )
            # startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            # tantileList.append("近24小时")
            # tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str)
            # item1={"cycleTime":24, "tantileList":tantileList}
            # resultList.append(tantileList)
            
            tantileList=[]
            tantileList.append("近7天")
            tantileList += [0,0,0,0,0,0,0]
            resultList.append(tantileList)
            tantileList=[]
            tantileList.append("近30天")
            tantileList += [0,0,0,0,0,0,0]
            resultList.append(tantileList)
        elif cycleType == "1":#按周
            startTime=endTime + timedelta( days = -7 )
        elif cycleType == "2":#按月
            startTime=endTime + timedelta( days = -30 )
        
        data_json = {"tantileList":resultList,"endTime":endTime_str,"startTime":startTime_str}
        self.write_json(data_json)

class GetWorkPointEventNumberHandler(BaseHandler):
    def get(self):
        resultList=[]
        sensorID = self.get_argument('workPointIDs')
        peakLimitCount_1=col_event.find({"sensorID":"01E2C847_01","eventType":1}).count()
        vibrationLimit1_1=col_event.find({"sensorID":"01E2C847_01","eventType":2}).count()
        vibrationLimit2_1=col_event.find({"sensorID":"01E2C847_01","eventType":3}).count()
        
        peakLimitCount_2=col_event.find({"sensorID":"01E2C847_03","eventType":1}).count()
        vibrationLimit1_2=col_event.find({"sensorID":"01E2C847_03","eventType":2}).count()
        vibrationLimit2_2=col_event.find({"sensorID":"01E2C847_03","eventType":3}).count()
        
        item1={"workPointID":"cddt5_001","workPointName":"5号线神九区间YDK28+900","peakLimitCount":peakLimitCount_1+peakLimitCount_2,\
               "vibrationLimit1":vibrationLimit1_1+vibrationLimit1_2,"vibrationLimit2":vibrationLimit2_1+vibrationLimit2_2}
        resultList.append(item1)
        item1={"workPointID":"gzsn_001","workPointName":"广州枢纽CK1+100","peakLimitCount":88456,\
               "vibrationLimit1":14238,"vibrationLimit2":14097}
        resultList.append(item1)
        
        
        peakLimitCount_1_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_01","eventType":1}).count()
        vibrationLimit1_1_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_01","eventType":2}).count()
        vibrationLimit2_1_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_01","eventType":3}).count()
        
        peakLimitCount_2_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_03","eventType":1}).count()
        vibrationLimit1_2_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_03","eventType":2}).count()
        vibrationLimit2_2_mqtt=col_event_mqtt.find({"sensorID":"01E4FA37_03","eventType":3}).count()
        
        item1={"workPointID":"cddt5_002","workPointName":"成都地铁5号线(事件回传)","peakLimitCount":peakLimitCount_1_mqtt+peakLimitCount_2_mqtt,\
               "vibrationLimit1":vibrationLimit1_1_mqtt+peakLimitCount_2_mqtt,"vibrationLimit2":vibrationLimit2_1_mqtt+vibrationLimit2_2_mqtt}
        resultList.append(item1)
        
        
        
        
        data_json = {"workPointList":resultList}
        self.write_json(data_json)

class GetWorkPointEventNumber4CycleTimeHandler(BaseHandler):
    def get(self):
        resultList=[]
        workPointIDs = self.get_argument('workPointIDs')
        cycleType = self.get_argument('cycleType')
        
        resultList=[]
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        
        if cycleType == "0":#按天
            current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0)
            
            #print(current_tiem)
            for i in range(24):
                countTimeEnd=current_tiem + timedelta( hours = (0-i) )
                countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
                countTimeBegin=current_tiem + timedelta(hours = (0-i-1) )
                countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
                #print("countTimeBegin_str")
                #print(countTimeBegin_str)
                #print("countTimeEnd_str")
                #print(countTimeEnd_str)
                #EndTimeList.append(countTimeEnd_str)
                #BeginTimeList.append(countTimeBegin_str)
                peakLimitEvent.append( col_event.find({"sensorID":"01E2C847_01","eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() + \
                                       col_event.find({"sensorID":"01E2C847_03","eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count())
                vibrationLimit1Event.append( col_event.find({"sensorID":"01E2C847_01","eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() + \
                                             col_event.find({"sensorID":"01E2C847_03","eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count())
                vibrationLimit2Event.append( col_event.find({"sensorID":"01E2C847_01","eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() + \
                                             col_event.find({"sensorID":"01E2C847_03","eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count())
                EndTimeList.append(countTimeEnd_str[0:19])
                BeginTimeList.append(countTimeBegin_str[11:16])
            EndTimeList.reverse()
            BeginTimeList.reverse()
            peakLimitEvent.reverse()
            vibrationLimit1Event.reverse()
            vibrationLimit2Event.reverse()
            item1={"workPointID":"cddt5_001",\
                     "workPointName":"5号线神九区间YDK28+900",\
                     "EndTimeList":EndTimeList,\
                     "BeginTimeList":BeginTimeList,\
                     "peakLimitEvent":peakLimitEvent,\
                     "vibrationLimit1Event":vibrationLimit1Event,\
                     "vibrationLimit2Event":vibrationLimit2Event}
            resultList.append(item1)
            peakLimitEvent=[149, 134, 118, 120, 139, 147, 126, 188, 190, 160, 124, 110, 121, 129, 138, 142, 130, 141, 109, 107, 156, 177, 190, 159]
            vibrationLimit1Event=[23, 19, 20, 22, 20, 22, 22, 29, 33, 25, 19, 21, 23, 20, 22, 19, 18, 13, 18, 19, 23, 26, 30, 25]
            vibrationLimit2Event=[23, 19, 19, 22, 20, 21, 22, 23, 29, 24, 18, 21, 23, 20, 21, 19, 18, 12, 17, 18, 22, 26, 28, 25]

            peakLimitEvent.reverse()
            vibrationLimit1Event.reverse()
            vibrationLimit2Event.reverse()
            item1={"workPointID":"gzsn_001",\
                     "workPointName":"广州枢纽CK1+100",\
                     "EndTimeList":EndTimeList,\
                     "BeginTimeList":BeginTimeList,\
                     "peakLimitEvent":peakLimitEvent,\
                     "vibrationLimit1Event":vibrationLimit1Event,\
                     "vibrationLimit2Event":vibrationLimit2Event}
            resultList.append(item1)
        elif cycleType == "1":#按周
            startTime=endTime + timedelta( days = -7 )
        elif cycleType == "2":#按月
            startTime=endTime + timedelta( days = -30 )
            
        data_json = {"resultList":resultList}
        self.write_json(data_json)

class GetTantileTop5WorkPointHandler(BaseHandler):
    def get(self):
        resultList=[]
        workPointIDs = self.get_argument('workPointIDs')
        cycleType = self.get_argument('cycleType')
        
        
        if cycleType == "0":#按天
            workPointIDs=["cddt5_001","gzsn_001"]
            workPointNames=["5号线神九区间YDK28+900","广州枢纽CK1+100"]
            tantileList=[]
            vibration_leve_co_name="vibration_leve_"+"01E2C847_01"
            vibration_leve_co_name_1="vibration_leve_"+"01E2C847_03"
        
            endTime = datetime.now().replace( microsecond=0,second=0,minute=0)
            endTime_str=endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            startTime=endTime + timedelta( hours = -24 )
            startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            
            sampleList=[]
            
            vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime_str,"$lte":endTime_str}}).sort([("samples_time",1)])
            
            for item_2 in vibration_leve_data:
                sampleList.append(item_2['vibration_leve'])
            vibration_leve_data.close()
            
            vibration_leve_data=col_vibration_leve[vibration_leve_co_name_1].find({"samples_time":{"$gte":startTime_str,"$lte":endTime_str}}).sort([("samples_time",1)])
            
            for item_2 in vibration_leve_data:
                sampleList.append(item_2['vibration_leve'])
            vibration_leve_data.close()
            
            sampleListLength=len(sampleList)
            #print(sampleListLength)
            sampleList.sort(reverse=True)
            resultNumber = int( 0.01*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
                
            resultNumber = int( 0.05*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
                
            resultNumber = int( 0.1*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
            
            resultNumber = int( 0.2*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
                
            resultNumber = int( 0.3*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
                
            resultNumber = int( 0.4*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
                
            resultNumber = int( 0.5*sampleListLength )
            if resultNumber < sampleListLength and resultNumber >= 0:
                tantileList.append( sampleList[resultNumber] )
            else:
                tantileList.append( "EOFError" )
            #print(tantileList)
            tantileList_1=[92.17, 66.53, 60.02, 59.41, 57.86, 56.92, 55.43]
            #temp_tantileList=[]
            #temp_tantileList.append(tantileList)
            #temp_tantileList.append(tantileList_1)
            #print(temp_tantileList)
            
            for j in range( len(tantileList) ):
                item3={}
                if tantileList[j] > tantileList_1[j]:
                    item3={"tantile_type":j,"number":1,"workPointID":workPointIDs[0],"workPointName":workPointNames[0],"tantile_dB":tantileList[j]}
                    resultList.append(item3)
                    item3={"tantile_type":j,"number":2,"workPointID":workPointIDs[1],"workPointName":workPointNames[1],"tantile_dB":tantileList_1[j]}
                    resultList.append(item3)
                else:
                    item3={"tantile_type":j,"number":1,"workPointID":workPointIDs[1],"workPointName":workPointNames[1],"tantile_dB":tantileList_1[j]}
                    resultList.append(item3)
                    item3={"tantile_type":j,"number":2,"workPointID":workPointIDs[0],"workPointName":workPointNames[0],"tantile_dB":tantileList[j]}
                    resultList.append(item3)
        elif cycleType == "1":#按周
            startTime=endTime + timedelta( days = -7 )
        elif cycleType == "2":#按月
            startTime=endTime + timedelta( days = -30 )
        # temp_item_1=[]
        # temp_item_2=[]
        # for n in range( len(resultList) ):
            # if number == 1:
                # temp_item_1.append({"workPointID":resultList[n]("workPointID"),"tantile_dB":resultList[n]("tantile_dB")})
             # else:
                # temp_item_2.append({"workPointID":resultList[n]("workPointID"),"tantile_dB":resultList[n]("tantile_dB")})
        # resultList=[]
        # resultList.append(temp_item_1)
        # resultList.append(temp_item_2)
        data_json = {"resultList":resultList}
        self.write_json(data_json)

class GetSpectrumCharacteristicHandler(BaseHandler):
    def get(self):
        resultList=[]
        sensorID = self.get_argument('sensorID')
        sensorID_old = transformationSensorID(sensorID)
        eventNum = self.get_argument('eventNum')
        centerFreqList=[1,1.25,1.6,2,2.5,3.15,4,5,6.3,8,10,12.5,16,20,25,31.5,40,50,63,80,100,125,160,200,250,315,400]
        bDList=[46.23084634,44.8226334,43.18718078,41.26605947,41.03780909,39.80854605,38.76839979,41.77464864,39.31305775,\
                42.50482687,50.55853104,60.75983053,63.34587449,62.66231309,65.97054064,67.10865387,70.38811865,70.44561269,\
                69.38361807,77.6267,82.37076987,75.84054564,69.35523345,63.76903366,62.29897576,60.31513209,57.26506674,]
        item={"centerFreqList":centerFreqList,"bDList":bDList}
        resultList.append(item)
        data_json = {"resultList":resultList}
        self.write_json(data_json)

class GetEventAndTantileByWorkPointIDHandler(BaseHandler):
    def get(self):
        resultList=[]
        workPointID = self.get_argument('workPointID')
        cycleType = self.get_argument('cycleType')
        
        current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0)
        endTime_str=current_tiem.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        
        startTime=current_tiem + timedelta( hours = -24 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        
        if workPointID == "cddt5_001":
            vibration_leve_co_name="vibration_leve_"+"01E2C847_01"
            peakLimitCount=col_event.find({"sensorID":"01E2C847_01","eventType":1,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            vibrationLimit1=col_event.find({"sensorID":"01E2C847_01","eventType":2,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            vibrationLimit2=col_event.find({"sensorID":"01E2C847_01","eventType":3,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            temp_tantileList=tantileCount("01E2C847_01", vibration_leve_co_name, startTime_str, endTime_str, 0)
            #temp_tantileList=[93.92,62.94,58.52,57.8,57.4,57.09,56.8]
            item1={"sensorID":"N19001025",\
                 "peakLimitCount":peakLimitCount,\
                 "vibrationLimit1":vibrationLimit1,\
                 "vibrationLimit2":vibrationLimit2,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
             
            vibration_leve_co_name="vibration_leve_"+"01E2C847_03"
            peakLimitCount=col_event.find({"sensorID":"01E2C847_03","eventType":1,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            vibrationLimit1=col_event.find({"sensorID":"01E2C847_03","eventType":2,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            vibrationLimit2=col_event.find({"sensorID":"01E2C847_03","eventType":3,"eventStartTime":{"$gte":startTime_str,"$lt":endTime_str}}).count()
            temp_tantileList=tantileCount("01E2C847_03", vibration_leve_co_name, startTime_str, endTime_str, 0)
            #temp_tantileList=[91.24,61.75,58.33,57.26,57.05,56.86,56.62]
            item1={"sensorID":"N19001027",\
                 "peakLimitCount":peakLimitCount,\
                 "vibrationLimit1":vibrationLimit1,\
                 "vibrationLimit2":vibrationLimit2,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001026",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001028",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"DH2620",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"DH2621",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"DH2622",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"DH2623",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
        elif workPointID == "gzsn_001":
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001033",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001034",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001035",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            temp_tantileList=[0,0,0,0,0,0,0]
            item1={"sensorID":"N19001036",\
                 "peakLimitCount":0,"vibrationLimit1":0,"vibrationLimit2":0,\
                 "tantile_1":temp_tantileList[0],"tantile_5":temp_tantileList[1],"tantile_10":temp_tantileList[2],\
                 "tantile_20":temp_tantileList[3],"tantile_30":temp_tantileList[4],"tantile_40":temp_tantileList[5],
                 "tantile_50":temp_tantileList[6],}
            resultList.append(item1)
            
            
        data_json = {"tantileList":resultList}
        self.write_json(data_json)